package com.netty.nettyaction;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @Description:
 * @Author: yangzhiwei
 * @Date: 2021/8/9 9:45
 */
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler {


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /*
        ChannelUnRegistered channe
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("已建立连接"); // channel已经被创建，但还未注册到 EvenLoop

        super.channelRegistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 当被通知channel是活跃的时候，发送一条消息
        // 当一个连接建立时被调用
        System.out.println("客户端已连接");
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",
                CharsetUtil.UTF_8));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(
                "Client received: " + byteBuf.toString(CharsetUtil.UTF_8));
    }
}
